package com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.fragment;

import android.annotation.SuppressLint;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;


import com.example.dante.a17376060_wanghaikang_finaltest.R;

import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.adapter.NewsAdapter;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.domain.News;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.useraction.Sousuo;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.utils.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.w3c.dom.Entity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FragmentNews extends Fragment {
    private View view;
    private SwipeRefreshLayout swipeRefreshLayout;
    public List<News> newsList = new ArrayList<>();
    String responseData;
    RecyclerView recyclerView;
    ImageView imageView;
    EditText editText;
    NewsAdapter newsAdapter;
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
                    newsAdapter = new NewsAdapter(newsList, getActivity());
                    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                    recyclerView.setAdapter(newsAdapter);
                    break;
            }
        }
    };

    @SuppressLint("ResourceAsColor")
    @Nullable
    @Override
    public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        view = inflater.inflate(R.layout.fragment_news, container, false);
        initView();
        swipeRefreshLayout = view.findViewById(R.id.refresh);
        swipeRefreshLayout.setColorSchemeColors(R.color.colorPrimary);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                NewsFresh();
            }
        });
        return view;
    }

    @SuppressLint("ResourceAsColor")
    private void initView() {
        recyclerView = view.findViewById(R.id.news);
        imageView = view.findViewById(R.id.sousuo);
        editText = view.findViewById(R.id.new_search);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(),Sousuo.class);
                intent.putExtra("news_title",editText.getText().toString());
                startActivity(intent);
            }
        });
        okhttp();
    }

    private void NewsFresh() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    Thread.sleep(1500);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initView();
                        newsAdapter.notifyDataSetChanged();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }
        }).start();
    }

    private void okhttp() {
        Log.d("测试","ok");
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpUtil.sendOkHttpRequest("http://47.101.175.33:8080/AndroidDataFinalTest/news_findAll.action", new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        responseData = response.body().string();
                        Log.d("测试",responseData);
                        parseJsonWithGsonObject(responseData);
                    }
                });
            }
        }).start();
    }

    private void parseJsonWithGsonObject(String responseData) {
        Gson gson = new Gson();
//        newsList.addAll((Collection<? extends News>) gson.fromJson(responseData, new TypeToken<List<News>>() {
//        }.getType()));
        newsList=gson.fromJson(responseData, new TypeToken<List<News>>() {
        }.getType());
        Message msg = new Message();
        msg.what = 1;
        handler.sendMessage(msg);
    }
}

